
/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.cms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.core.vo.CardVO;
import vip.xiaonuo.modular.cms.entity.Template;
import vip.xiaonuo.modular.cms.param.TemplateParam;
import vip.xiaonuo.modular.cms.service.TemplateService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 前端模板控制器
 *
 * @author liubaihan
 * @date 2022-07-01 15:25:28
 */
@Controller
public class TemplateController {

    private String PATH_PREFIX = "cms/templateManage/";

    @Resource
    private TemplateService templateService;

    @Autowired
    private HttpServletRequest request;

    @Value("${cms.templatePath}")
    private String templatePath;


    /**
     * 前端模板页面
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @GetMapping("/template/index")
    public String index() {
        return PATH_PREFIX + "index.html";
    }

    /**
     * 前端模板表单页面
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    @GetMapping("/template/form")
    public String form() {
        return PATH_PREFIX + "form.html";
    }

    /**
     * 查询前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @GetMapping("/template/page")
    @BusinessLog(title = "前端模板_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public PageResult<CardVO> page(TemplateParam templateParam) {
        PageResult<Template> templatePageResult = templateService.page(templateParam);

        Page<CardVO> cardVOPage = new Page<>(templatePageResult.getPage(),templatePageResult.getLimit(),templatePageResult.getCount());

        List<CardVO> cardVOS = new ArrayList<>();
        templatePageResult.getData().forEach(template -> {
            CardVO cardVO = CardVO.builder()
                    .id(template.getId().toString())
                    .image(template.getImageSrc())
                    .title(template.getTemplateName())
                    .remark(template.getAuthor())
                    .time(DateUtil.format(template.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN))
                    .status(template.getStatus())
                    .build();
            cardVOS.add(cardVO);
        });

        cardVOPage.setRecords(cardVOS);
        PageResult<CardVO> cardVOPageResult = new PageResult<>(cardVOPage);
        return cardVOPageResult;
    }

    /**
     * 添加前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @PostMapping("/template/add")
    @BusinessLog(title = "前端模板_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(TemplateParam.add.class) TemplateParam templateParam) {
        templateService.add(templateParam);
        return new SuccessResponseData();
    }

    /**
     * 删除前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @PostMapping("/template/delete")
    @BusinessLog(title = "前端模板_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(TemplateParam.delete.class) List<TemplateParam> templateParamList) {
        templateService.delete(templateParamList);
        return new SuccessResponseData();
    }

    /**
     * 编辑前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @PostMapping("/template/edit")
    @BusinessLog(title = "前端模板_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(TemplateParam.edit.class) TemplateParam templateParam) {
        templateService.edit(templateParam);
        return new SuccessResponseData();
    }

    /**
     * 查看前端模板
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @GetMapping("/template/detail")
    @BusinessLog(title = "前端模板_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(TemplateParam.detail.class) TemplateParam templateParam) {
        return new SuccessResponseData(templateService.detail(templateParam));
    }

    /**
     * 前端模板列表
     *
     * @author liubaihan
     * @date 2022-07-01 15:25:28
     */
    
    @ResponseBody
    @GetMapping("/template/list")
    @BusinessLog(title = "前端模板_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(TemplateParam templateParam) {
        return new SuccessResponseData(templateService.list(templateParam));
    }

    /**
     * 下架，启用模板
     *
     */
    @GetMapping("/enableTemplate/{id}/{status}")
    @ResponseBody
    public ResponseData enableTemplate(@PathVariable("id") String id,
                                       @PathVariable("status") String status){
        Template template = templateService.getById(id);
        template.setStatus(status);

        if(status.equals("1")){
            Template alreadyTemplate = templateService.getOne(new LambdaQueryWrapper<Template>().eq(Template::getStatus, "1"));
            if(BeanUtil.isNotEmpty(alreadyTemplate)){
                alreadyTemplate.setStatus("2");
                templateService.updateById(alreadyTemplate);
            }
        }

        return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE,"模板启用成功",templateService.updateById(template));
    }

    /**
     * 上传模板文件
     *
     * @param multipartFile: 模板文件
     * @return:
     * @author: liubaihan
     * @date: 2022/7/14 13:53
     */
    @PostMapping("/uploadTemplate")
    @ResponseBody
    public ResponseData uploadTemplate(@RequestParam("file") MultipartFile multipartFile){
        Boolean isSuccess = this.templateService.upload(multipartFile);
        return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE,"模板上传成功",isSuccess);
    }

    @GetMapping("/editTemplate/{id}")
    public String editTemplate(@PathVariable("id")String id){
        request.setAttribute("templateId",id);
        return PATH_PREFIX + "templateIndex.html";
    }

    @GetMapping("/getFileTree")
    @ResponseBody
    public ResponseData getFileTree(@RequestParam("templateId") String templateId,
                                    @RequestParam("oper") String oper,
                                    @RequestParam(value = "path",required = false) String path,
                                    HttpServletResponse response) throws IOException {
        //文件树格式
        if(oper.equals("list")){
            return this.templateService.getTreeList(templateId);
        }
        if(oper.equals("content")){
            path = templatePath + path;
            System.out.println(path.replace("\\","/"));
            System.out.println(StrUtil.replace(path,"/","\\"));
            System.out.println(FileUtil.exist(path));
            BufferedInputStream bufferedOutputStream = FileUtil.getInputStream(path);

            ServletOutputStream out = response.getOutputStream();

            byte buff[] = new byte[1024];
            int length = 0;

            while ((length = bufferedOutputStream.read(buff)) > 0) {
                out.write(buff,0,length);
            }
            bufferedOutputStream.close();

            out.close();

            out.flush();

            return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE,"查询成功","");
        }
        return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE,"查询成功","");
    }


    @PostMapping("/getFileTree")
    @ResponseBody
    public ResponseData saveFile(@RequestParam("templateId") String templateId,
                                    @RequestParam("oper") String oper,
                                    @RequestParam(value = "path",required = false) String path,
                                    @RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
        if(oper.equals("create")){
            File fileInfo = FileUtil.newFile(templatePath + path);
            fileInfo.createNewFile();
        }if(oper.equals("delete")){
            FileUtil.del(templatePath + path);
        }
        if(oper.equals("save")){
            FileUtil.writeBytes(file.getBytes(),templatePath+path);
        }
        return new SuccessResponseData();
    }

}
